const axios = require('axios');
const xml2js = require('xml2js');
const wxApisConfig = require('../../../config/wxapi.json');
const { generateRandomUUID } = require('../tool/common');
const security = require('../../service/security');
const wxApiError = require('../error/wxapierror');
const https = require('https');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
/**
 * 构建xml解析工具
 * @returns {*[]}
 */
function getXmlTool () {
    let xmlBuilder = new xml2js.Builder({
        cdata: true,
        rootName: 'xml',
        headless: true
    });
    let xmlParser = new xml2js.Parser({
        explicitArray: false,
        cdata: true,
        rootName: 'xml',
        headless: true
    });
    return [xmlBuilder, xmlParser];
}

/**
 * 企业付款到零钱
 * @param transferOrderId
 * @param openid
 * @param amount
 * @param description
 * @returns {Promise<*>}
 */
async function transferMoneyToUser (transferOrderId, openid, amount, description) {
    let [xmlBuilder, xmlParser] = getXmlTool();
    let queryData = {
        mch_appid: wxApisConfig.secret.appId,
        mchid: wxApisConfig.payment.mchId,
        partner_trade_no: transferOrderId,
        openid: openid,
        check_name: 'NO_CHECK',
        amount: amount,
        desc: description,
        nonce_str: generateRandomUUID()
    };
    queryData.sign = security.generateOrderSign(queryData, true);
    let xmlData = xmlBuilder.buildObject(queryData);
    let httpAgent;
    try {
        httpAgent = new https.Agent({
            cert: fs.readFileSync(path.resolve(__dirname, '../../auth/apiclient_cert.pem')),
            key: fs.readFileSync(path.resolve(__dirname, '../../auth/apiclient_key.pem'))
        });
    } catch (e) {
        throw new wxApiError.RequestTransferError('证书读取失败');
    }
    let response = await axios.post(wxApisConfig.apis.payToUserUrl, xmlData, { httpsAgent: httpAgent });
    let returnData = await xmlParser.parseStringPromise(response.data);
    if (returnData.xml.return_code === 'SUCCESS' && returnData.xml.result_code === 'SUCCESS') {
        return returnData.xml.payment_no;
    } else {
        console.warn('transferMoneyToUser error: ', returnData.xml);
        throw new wxApiError.RequestTransferError(returnData.xml.err_code_des);
    }
}

module.exports = {
    getXmlTool,
    transferMoneyToUser
};
